import {defineStore} from 'pinia'
import router from '@/router/index.js'

// 菜单标签页状态管理
export const useMenuTabStore = defineStore('menuTab', {

    // 定义状态
    state: () => ({
        skLoading:true,
        activePath:"/dashboard",
        menuList:[]
    }),

    // 定义动作
    actions: {
        // 点击改变菜单
        changeMenuTab(path){
            this.activePath = path
            router.push(path)
        },

        // 清空
        clearTabs(){
            this.skLoading = false
            this.menuList = []
        },

        // 添加菜单
        addMenuTab({name,path}){
            if (name && path){
                // 查找当前路径
                const index = this.menuList.findIndex(m=>m.path===path)
                // 激活当前路径
                this.activePath = path
                if (index === -1 && path !== '/login' && name !== 'NotFound'){
                    this.menuList.push({name,path})
                    // 根据配置显示指定的菜单个数
                    // if ( this.menuList.length  <= 5){
                    //     this.menuList.push({name,path})
                    // }else{
                    //     this.menuList.slice(0, 5);
                    // }
                }
            }
        },

        // 移除菜单
        removeMenuTab(path){
            // 获取菜单列表
            const tabs = this.menuList
            // 获取激活路径
            let activeTabPath = this.activePath
            // 判断激活路径是否等于当前路径
            if (activeTabPath === path) {
                tabs.forEach((tab, index) => {
                    if (tab.path === path) {
                        const nextTab = tabs[index + 1] || tabs[index - 1]
                        if (nextTab) {
                            activeTabPath = nextTab.path
                        }
                    }
                })
            }

            // 获取激活的路径
            this.activePath = activeTabPath
            // 查找当前路径
            const index = this.menuList.findIndex(m=>m.path===path)
            // 删除当前路径
            this.menuList.splice(index,1)
            // 路由跳转到激活路径
            router.push(activeTabPath)
        }
    },

    // 持久化存储
    persist: {
        key: 'kong-pinia-menutabs',
        storage: localStorage, // sessionStorage
    }
})
